package com.zhaorujie.rpc.core.remoting.netty.codec;

import com.zhaorujie.rpc.core.exception.RpcException;
import com.zhaorujie.rpc.core.remoting.common.Constant;
import com.zhaorujie.rpc.core.serialize.RpcSerialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * @author 赵汝杰
 * @version v1.0
 * @description NettyDecoder
 * @date 2024/3/5
 **/
public class NettyDecoder extends ByteToMessageDecoder {

    private final static Logger log = LoggerFactory.getLogger(NettyDecoder.class);

    private final Class<?> genericClass;
    private final RpcSerialize rpcSerialize;

    public NettyDecoder(Class<?> genericClass, RpcSerialize rpcSerialize) {
        this.genericClass = genericClass;
        this.rpcSerialize = rpcSerialize;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            log.error("可读字节长度小于4");
            return;
        }
        in.markReaderIndex();
        byte magic = in.readByte();
        if (!Objects.equals(magic, Constant.MAGIC)) {
            log.error("协议魔数不正确...");
            throw new RpcException("协议不正确");
        }
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            log.error("数据长度不正确");
            return;
        }
        byte[] data = new byte[dataLength];

        in.readBytes(data);

        Object object = rpcSerialize.deserialize(data, genericClass);
        out.add(object);
    }
}
